﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using HRM.HRMServiceProxy;
using System.Collections;

namespace HRM
{
    public partial class frmEmployeeShiftList : DockContent
    {
        ListView listView1 = new ListView();
        int _BranchID = 0;
        int _departmentID = 0;
        MainServiceClient _wcfMain;
        EmployeeShiftClient _wcfES;
        EmployeeShiftInfo _ESInfo;
        BranchClient _wcfBranch;
        DepartmentClient _wcfDepartment;
        EmployeeClient _wcfEmployee;
        ShiftClient _wcfShift;
        ParameterClient _wcfPara;
        DataGridViewTextBoxColumn col;
        int _CloseBookDay;
        DateTime _date;
        RoleRightInfo listRole;
        DateTime _dateVal = DateTime.MinValue;
        public frmEmployeeShiftList()
        {
            InitializeComponent();

            listRole = UIParamater.Quyen_BangPhanCa;
            Language();

            _wcfEmployee = Service.Employee();
            _wcfMain = Service.MainService();
            _wcfBranch = Service.Branch();
            _wcfDepartment = Service.Department();
            _wcfES = Service.EmployeeShift();
            _wcfPara = Service.Parameter();
            _wcfEmployee = Service.Employee();
            _wcfShift = Service.Shift();

            _CloseBookDay = Convert.ToInt32(_wcfPara.Parameter_GetByName("CloseBook").Value);           
           

            UISetting.LoadTreeView3(ref tvBranch);
        }

        private void Language()
        {
            if (this.Tag != null)
                this.TabText = UpdateUI.GetString(this.Tag.ToString());
            UpdateUI.Load_ToolStrip(ref toolStrip1);
        }

        private void tvBranch_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Level == 0)
            {
                _BranchID = 0;
                _departmentID = 0;
                LoadData();
            }
            else if (e.Node.Level == 1)
            {
                _BranchID = Convert.ToInt32(e.Node.Tag);
                _departmentID = 0;
                LoadData();
            }
            else if (e.Node.Level >= 2)
            {
                _departmentID = Convert.ToInt32(e.Node.Tag);
                _BranchID = Convert.ToInt32(e.Node.Parent.Tag);
                LoadData();
            }
        }

        private void LoadData()
        {
            // Add nhân viên theo vào Datagridview:
            dgvEmployeeShift.Columns.Clear();
            DataTable dtEmployee = _wcfES.EmployeeShift_GetEmployee(_departmentID).Tables[0];
            dgvEmployeeShift.DataSource = dtEmployee;
            dgvEmployeeShift.Columns["FullName"].Frozen = true;
            dgvEmployeeShift.Columns["RowNumber"].Visible = true;
            dgvEmployeeShift.Columns["RowNumber"].HeaderText = UpdateUI.GetString("stt");
            dgvEmployeeShift.Columns["Employee_IsOfficer"].Visible = false;
            dgvEmployeeShift.Columns["RowNumber"].Width = 50;
            dgvEmployeeShift.Columns["RowNumber"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgvEmployeeShift.Columns["Employee_ID"].Visible = false;
            dgvEmployeeShift.Columns["Employee_CardNo"].Visible = false;
            dgvEmployeeShift.Columns["FullName"].HeaderText = UpdateUI.GetString("hovaten");
            dgvEmployeeShift.Columns["FullName"].Width = 180;

            // Sử dụng Dictionary:
            Dictionary<int, int> dicEmployeeRef = new Dictionary<int, int>();
            for (int counter = 0; counter < dtEmployee.Rows.Count; counter++)
            {
                dicEmployeeRef.Add(Convert.ToInt32(dtEmployee.Rows[counter]["Employee_ID"]), counter);
            }

            // Add columnbox vào Datagridview:
            AddCombobox();

            //Auto Insert Employee is Shift HC
            if (_departmentID > 0)
                for (int x = 0; x <= dgvEmployeeShift.Rows.Count - 1; x++)
                {
                    if (Convert.ToBoolean(dtEmployee.Rows[x]["Employee_IsOfficer"]))
                    {
                        _wcfES.EmployeeShift_InsertAutoShiftHC(_departmentID, _dateVal, _dateVal.AddDays(6));
                    }
                }

            // Hiển thị dữ liệu ra Datagridview:
            DataTable dtShiftTable = _wcfES.EmployeeShift_GetList(_departmentID, _dateVal).Tables[0];
            int RowIdx = 0;
            int DayValue = 0;
            
            foreach (DataRow dr in dtShiftTable.Rows)
            {
                if (dicEmployeeRef.ContainsKey(Convert.ToInt32(dr["EmployeeShift_EmployeeID"])))
                {
                    RowIdx = dicEmployeeRef[Convert.ToInt32(dr["EmployeeShift_EmployeeID"])];
                    DayValue = Convert.ToDateTime(dr["EmployeeShift_Date"]).Day;
                    if (dgvEmployeeShift.Rows[RowIdx].Cells[DayValue.ToString()].Value != null)
                    {
                        dgvEmployeeShift.Rows[RowIdx].Cells[DayValue.ToString()].Value += "," + dr["Shift_Name"];
                        dgvEmployeeShift.Rows[RowIdx].Cells[DayValue.ToString()].Tag += "," + dr["EmployeeShift_ShiftID"];
                    }
                    else
                    {
                        dgvEmployeeShift.Rows[RowIdx].Cells[DayValue.ToString()].Value = dr["Shift_Name"];
                        dgvEmployeeShift.Rows[RowIdx].Cells[DayValue.ToString()].Tag = dr["EmployeeShift_ShiftID"];
                    }
                }
            }
            
        }

        private void AddCombobox()
        {
            string _DayOfWeek;
            _dateVal = DateTime.ParseExact(dtpDate.Value.ToString("dd/MM/yyyy"), "dd/MM/yyyy", null);

            //chuyển về ngày đầu tuần
            _dateVal = _dateVal.AddDays(1 - Convert.ToInt16(_dateVal.DayOfWeek.ToString("D")));
            //dtpDate.Value = _dateVal;
            _date = _dateVal;

            //Danh sách các ngày trong tuần
            List<DateTime> lstDate = new List<DateTime>();
            while (_date <= _dateVal.AddDays(6))
            {
                lstDate.Add(_date);
                _date = _date.AddDays(1);
            }

            // Dữ liệu trắng cho textbox trong dgv
            foreach (DateTime dt in lstDate)
            {
                _DayOfWeek = UISetting.GetDayOfWeek(dt);
                col = new DataGridViewTextBoxColumn();
                col.Name = dt.Day.ToString();
                col.HeaderText = _DayOfWeek + " (" + dt.ToString("dd/MM/yyyy") + ")";
                col.Width = 100;
                dgvEmployeeShift.Columns.Add(col);
            }

            //Danh sách các ca làm việc theo phòng ban
            DataTable dtShift = _wcfShift.Shift_GetAllByDepartment(_departmentID).Tables[0];

            listView1.Clear();
            listView1.View = View.Details;
            listView1.CheckBoxes = true;
            listView1.Columns.Add("Col1");
            listView1.AutoArrange = true;

            listView1.HeaderStyle = ColumnHeaderStyle.None;
            listView1.Visible = false;

            this.Controls.Remove(listView1);
            this.dgvEmployeeShift.Controls.Add(listView1);
            for (int i = 0; i < dtShift.Rows.Count; i++)
            {
                ListViewItem lv = new ListViewItem(new string[] { dtShift.Rows[i]["Shift_Name"].ToString() });
                lv.Tag = dtShift.Rows[i]["Shift_ID"].ToString();

                listView1.Items.Add(lv);
            }

        }

        private void dgvEmployeeShift_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            switch (e.ColumnIndex)
            {
                case 4:
                case 5:
                case 6:
                case 7:
                case 8:
                case 9:
                case 10:
                case 11:

                    Rectangle rect = this.dgvEmployeeShift.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true);
                    listView1.Location = rect.Location;
                    listView1.Width = rect.Width;
                    listView1.Height = this.dgvEmployeeShift.Height / 4;

                    string[] IDs = new string[] { "" };
                    if (this.dgvEmployeeShift.CurrentCell.Tag != null)
                        IDs = this.dgvEmployeeShift.CurrentCell.Tag.ToString().Split(new char[] { ',' });

                    foreach (string item in IDs)
                    {
                        for (int i = 0; i < listView1.Items.Count; i++)
                        {
                            if (listView1.Items[i].Tag.ToString() == item)
                                listView1.Items[i].Checked = true;
                        }
                    }

                    //Đặt độ rộng cho listview
                    for (int i = 0; i < dgvEmployeeShift.Rows.Count; i++)
                    {
                        listView1.Columns[0].Width = dgvEmployeeShift.Columns[i].Width;
                    }
                    listView1.Visible = true;
                    break;
            }
        }

        private void dgvEmployeeShift_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            switch (e.ColumnIndex)
            {
                case 4:
                case 5:
                case 6:
                case 7:
                case 8:
                case 9:
                case 10:
                case 11:

                    string s = "";
                    string ID = "";
                    if (listView1.CheckedItems.Count == 0)
                    {
                        this.dgvEmployeeShift.CurrentCell.Value = s;
                        this.dgvEmployeeShift.CurrentCell.Tag = ID;
                    }
                    else
                    {
                        for (int i = 0; i < listView1.CheckedItems.Count; i++)
                        {
                            if (s.Length > 0)
                            {
                                s += "," + listView1.CheckedItems[i].SubItems[0].Text;
                                ID += "," + listView1.CheckedItems[i].Tag;
                            }
                            else
                            {
                                s = listView1.CheckedItems[i].SubItems[0].Text;
                                ID = listView1.CheckedItems[i].Tag.ToString();
                            }


                            this.dgvEmployeeShift.CurrentCell.Value = s;
                            this.dgvEmployeeShift.CurrentCell.Tag = ID;
                        }

                        


                    }
                    
                    //Khóa columns
                    this.listView1.Visible = false;
                    for (int i = 0; i < listView1.Items.Count; i++)
                    {
                        listView1.Items[i].Checked = false;
                    }
                    break;

            }

           ArrayList AL =  ArrayShift();
           string strStartTime = "";
            string strEndTime = "";
            bool IsValid = true;
            int counter = 1;
            DateTime dtEndTimeOfLastShift;
            DateTime dtStartTimeOfShift;
           if (AL.Count > 0)
           {               
               strEndTime = AL[0].ToString().Substring(8);
               dtEndTimeOfLastShift = DateTime.ParseExact("1/1/2009 " + strEndTime, "d/M/yyyy HH:mm", null);

               while ((counter < AL.Count) && (IsValid))
               {
                   strStartTime = AL[counter].ToString().Substring(0, 5);
                   dtStartTimeOfShift = DateTime.ParseExact("1/1/2009 " + strStartTime, "d/M/yyyy HH:mm", null);
                   if (dtStartTimeOfShift < dtEndTimeOfLastShift)
                       IsValid = false;
                   else
                   {
                       strEndTime = AL[counter].ToString().Substring(8);
                       dtEndTimeOfLastShift = DateTime.ParseExact("1/1/2009 " + strEndTime, "d/M/yyyy HH:mm", null);
                       if (strStartTime.CompareTo(strEndTime) > 0)
                       {
                           dtEndTimeOfLastShift = dtEndTimeOfLastShift.AddDays(1);
                       }
                       counter++;
                   }
               }
           }
           if (!IsValid)
           {
               MessageBox.Show("Các ca không hợp lệ!", UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
               this.dgvEmployeeShift.CurrentCell.Value = "";
               this.dgvEmployeeShift.CurrentCell.Tag = "";
           }
        }
        private ArrayList ArrayShift()
        {
            ShiftClient _wcfShift = Service.Shift();
            ArrayList ALshift = new ArrayList(); ;

            string[] _shiftID = null;
            _shiftID = dgvEmployeeShift.CurrentCell.Tag.ToString().Split(new char[] { ',' });

            if (_shiftID.Length > 1)
            {
                for (int j = 0; j < _shiftID.Length; j++)
                {
                    if (_shiftID[j].Trim().Length > 0)
                    {
                        ALshift.Add(_wcfShift.Shift_GetInfo(Convert.ToInt32(_shiftID[j])).TimeIn + " - " + _wcfShift.Shift_GetInfo(Convert.ToInt32(_shiftID[j])).TimeOut);
                    }
                }
            }
            ALshift.Sort();
            return ALshift;
        }

        private bool ShiftIsValid()
        {


            return true;
        }

        private void dgvEmployeeShift_Scroll(object sender, ScrollEventArgs e)
        {
            switch (dgvEmployeeShift.CurrentCell.ColumnIndex)
            {
                case 4:
                case 5:
                case 6:
                case 7:
                case 8:
                case 9:
                case 10:
                case 11:
                    if (listView1.Visible == true)
                    {
                        Rectangle r = this.dgvEmployeeShift.GetCellDisplayRectangle(this.dgvEmployeeShift.CurrentCell.ColumnIndex, this.dgvEmployeeShift.CurrentCell.RowIndex, true);
                        listView1.Location = r.Location;
                        listView1.Width = r.Width;
                        listView1.Height = dgvEmployeeShift.Height / 4;
                    }
                    break;
            }
        }

        private void frmEmployeeShiftList_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Escape:
                    this.Dispose();
                    this.Close();
                    break;
                case Keys.F3:
                    btnSave_Click(null, null);
                    break;
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            bool isUpdate = true;
            if (!listRole.Update)
            {
                MessageBox.Show(UpdateUI.GetString("khongcoquyencapnhat"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (_departmentID == 0)
            {
                MessageBox.Show(UpdateUI.GetString("banchuachonphongban"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            dgvEmployeeShift.EndEdit();
            _date = DateTime.ParseExact(dtpDate.Value.ToString("dd/MM/yyyy"), "dd/MM/yyyy", null);
            _date = _dateVal.AddDays(1 - Convert.ToInt16(_dateVal.DayOfWeek.ToString("D")));
            List<DateTime> lstDate = new List<DateTime>();
            while (_date <= _dateVal.AddDays(6))
            {
                lstDate.Add(_date);
                _date = _date.AddDays(1);
            }

            _wcfES.EmployeeShift_DeleteEmployee(_departmentID);

            DataTable dtEmpl = _wcfES.EmployeeShift_GetEmployee(_departmentID).Tables[0];
            foreach (DateTime date in lstDate)
            {
                for (int i = 0; i <= dtEmpl.Rows.Count - 1; i++)
                {
                    _ESInfo = new EmployeeShiftInfo();
                    _ESInfo.DepartmentID = _departmentID;
                    _ESInfo.EmployeeID = Convert.ToInt32(dtEmpl.Rows[i]["Employee_ID"].ToString());
                    _ESInfo.Date = date;



                    DataGridViewTextBoxCell com = (DataGridViewTextBoxCell)dgvEmployeeShift.Rows[i].Cells[date.Day.ToString()];
                    string[] _shiftID = null;

                    if (com.Tag != null)
                    {
                        _shiftID = com.Tag.ToString().Split(new char[] { ',' });

                        if (_shiftID.Length > 0)
                        {
                            for (int j = 0; j < _shiftID.Length; j++)
                            {
                                if (_shiftID[j].Trim().Length > 0)
                                    _ESInfo.ShiftID = Convert.ToInt32(_shiftID[j]);

                                if (_ESInfo.ShiftID > 0)
                                {
                                    ShiftInfo _shiftInfo = _wcfShift.Shift_GetInfo(_ESInfo.ShiftID);

                                    if (_shiftInfo.TimeIn != "")
                                        _ESInfo.TimeIn = DateTime.ParseExact(date.ToString("dd/MM/yyyy") + " " + _shiftInfo.TimeIn, "dd/M/yyyy HH:mm", null);
                                    if (_shiftInfo.TimeOut != "")
                                        _ESInfo.TimeOut = DateTime.ParseExact(date.ToString("dd/MM/yyyy") + " " + _shiftInfo.TimeOut, "dd/M/yyyy HH:mm", null);
                                    if (_shiftInfo.TimeInB != "")
                                        _ESInfo.TimeInB = DateTime.ParseExact(date.ToString("dd/MM/yyyy") + " " + _shiftInfo.TimeInB, "dd/M/yyyy HH:mm", null);
                                    if (_shiftInfo.TimeOutB != "")
                                        _ESInfo.TimeOutB = DateTime.ParseExact(date.ToString("dd/MM/yyyy") + " " + _shiftInfo.TimeOutB, "dd/M/yyyy HH:mm", null);
                                    _ESInfo.ID = _wcfES.EmployeeShift_Insert(_ESInfo);
                                    if (_ESInfo.ID <= 0)
                                    {
                                        isUpdate = false;
                                    }

                                }
                            }
                        }
                    }
                }

            }
            if (isUpdate)
                Program.taskbarNotifier.Show(UpdateUI.GetString("thongbao"), UpdateUI.GetString("capnhatthanhcong"), UIParamater.TIME_MOVE_UP, UIParamater.TIME_SHOW, UIParamater.TIME_MOVE_DOWN);
            else
                MessageBox.Show(UpdateUI.GetString("capnhatkhongthanhcong"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);

        }

        private void frmEmployeeShiftList_Activated(object sender, EventArgs e)
        {
            Language();
            if (dgvEmployeeShift.Columns.Count > 0)
            {
                dgvEmployeeShift.Columns["FullName"].HeaderText = UpdateUI.GetString("hovaten");
                dgvEmployeeShift.Columns["RowNumber"].HeaderText = UpdateUI.GetString("stt");
            }
        }

        private void dgvEmployeeShift_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            LoadData();
        }

        private void dtpDate_ValueChanged(object sender, EventArgs e)
        {
            LoadData();
        }


    }
}
